package com.chenye.rabbitmq.rabbit;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * Created by chenye on 2018/4/15.
 */
@Component
@Slf4j
@RabbitListener(containerFactory = "firstFactory")
public class HelloRecevier {

    @RabbitListener(queues = "hello")
    @RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver 1 : " + hello);
    }

    @RabbitListener(queues = "user")
    @RabbitHandler
    public void process1(User user) {
        System.out.println(user.getName());
        System.out.println("Receiver 1 : " + user.toString());
    }


    @RabbitListener(queues = RabbitConfig.MESSAGE)
    @RabbitHandler
    public void message(String message) {
        System.err.println("Receiver message : " + message);
    }
    @RabbitListener(queues = RabbitConfig.MESSAGES)
    @RabbitHandler
    public void messages(String message) {
        System.err.println("Receiver messages : " + message);
    }
    @RabbitListener(queues = "fanout.A")
    @RabbitHandler
    public void fanoutA(String message) {
        System.err.println("Receiver a : " + message);
    }

    @RabbitListener(queues = "fanout.B")
    @RabbitHandler
    public void fanoutB(String message) {
        System.err.println("Receiver b : " + message);
    }
    @RabbitListener(queues = "fanout.C")
    @RabbitHandler
    public void fanoutC(String message) {
        System.err.println("Receiver c : " + message);
    }


    @RabbitListener(queues = RabbitConfig.REPEAT_TRADE_QUEUE)
    @RabbitHandler
    public void dxlMessage(String test) {
        System.err.println("Receiver c : " + test);
        System.err.println(new Date());
    }

    /*rabbitmq
    *   ack机制测试
    *   在第一次抛出异常后，消息没有丢失，继续往消费者端发送
    * */
    private static int num = 0;
    @RabbitListener(queues = "message.center.create")
    @RabbitHandler
    public void ttlMessage(Message message, Channel channel) throws IOException {
        System.err.println("Receiver c : " + new String(message.getBody()));
        System.err.println(new Date());
        if(num==0){
            num++;
            throw new RuntimeException("zero number");
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
